import 'dart:async';
import 'dart:math';

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mtf/app/base/BaseController.dart';
import 'package:mtf/app/data/UsdRecordEntity.dart';
import 'package:mtf/app/net/HttpManger.dart';
import 'package:mtf/app/routes/app_pages.dart';
import 'package:mtf/app/widget/lineK/chart_style.dart';
import 'package:mtf/app/widget/lineK/entity/k_line_entity.dart';
import 'package:mtf/app/widget/lineK/utils/data_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../theme/app_colors.dart';
import '../../utils/AppUtils.dart';
import '../../utils/cache/AppCahche.dart';
import '../home_module/home_controller.dart';
import '../home_module/home_controller.dart';
/**
 * GetX Template Generator - fb.com/htngu.99
 * */

class stockMarketController extends BaseController with StateMixin {
  RxList<KLineEntity> datas = <KLineEntity>[].obs;
  RxList<ListUSDElement> usdList = <ListUSDElement>[].obs;
  RefreshController refreshController =
      RefreshController(initialRefresh: false);
  var rateDay = "".obs;
  var rateDiffPrice = "".obs;
  var selectTypeObs=0.obs;
  var startTimeObs="".obs;
  var endTimeObs="".obs;
  var selectTabObs=0.obs;

  @override
  void onInit() {
    super.onInit();
    change(null, status: RxStatus.loading());
    getNetData();
    startTimer();
  }

  void selectTab(int tab) async{
    selectTabObs.value = tab;
    change(null, status: RxStatus.success());
  }

  void clickTransactionRecord() {
    AppUtils.authAndMt5Check(() {
      Get.toNamed(Routes.TRANSACTION_RECORD);
    });
  }

  void getNetData({bool? emptyDialog}) async {
    if(AppCache.isLogin()){
      if(emptyDialog!=null){
        showLoading();
      }
      var resp = await HttpManager.reqLastTick(0,selectTypeObs.value);
      if (resp.isSuccessData()) {
        var dataList = resp.data!.info
            .map((e) => KLineEntity(
            double.parse(e.priceOpen ?? "0.00"),
            //开
            double.parse(e.askHigh ?? "0.00"),
            //当天的最高出价
            double.parse(e.askLow ?? "0.00"),
            //当天的最低出价
            double.parse(e.priceClose ?? "0.00"),
            //关闭数量
            double.parse(e.volume ?? "0.00"),
            //成交量
            0,
            //股票数量
            0,
            0,
            double.parse(e.bid ?? "0.00"),
            //买价格
            double.parse(e.ask ?? "0.00"),
            //卖价格
            e.datetime))
            .toList();
        print('getNetData${dataList.length}');
        DataUtil.calculate(dataList);
        datas.assignAll(dataList);
        if (!resp.data!.info.isEmpty) {
          rateDay.value = "${resp.data!.info.last.rateDay}" ?? "";
          rateDiffPrice.value =
              resp.data!.info.last.rateDiffPrice.toString() ?? "";
        }
      }
      hideLoading();
      if(AppCache.getUserInfo()!=null&&AppCache.getUserInfo().mt5Login!=null){
        var usdResp = await HttpManager.reqUsdRecord(1);
        if (usdResp.isSuccessData()) {
          usdList.assignAll(usdResp.data!.list);
        }
      }
      change(null, status: RxStatus.success());
      refresh();
      refreshController.refreshCompleted();
    }else{
      change(null, status: RxStatus.success());
    }


  }

  KLineEntity lastData() {
    if (!datas.isEmpty) {
      return datas.last;
    } else {
      return KLineEntity(
          0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0, 0, 0.00, 0.00, "");
    }
  }

  Color curColor() {
    return lastData().close >= lastData().open
        ? ChartColors.upColor
        : ChartColors.dnColor;
  }

  Color judgeColor(String value) {
    if (value.isEmpty) {
      return ChartColors.upColor;
    }
    return double.parse(value) < 0 ? ChartColors.upColor : ChartColors.dnColor;
  }

  late Timer timer;

  void startTimer() {
    print('startTimer');
    // Timer.periodic方法可以反复执行，这里设置执行周期为60s
    var Controller=GetInstance().find<homeController>();
    timer = Timer.periodic(const Duration(seconds: 15), (timer) {
      var currentPage=Get.currentRoute;
      if(currentPage==Routes.HOME){
        if (AppCache.isLogin()) {
          if(Controller.currentPage==1&&selectTypeObs.value==0){
            getNetData();
          }
        } else {
          timer.cancel();
        }
      }
    });

  }

  @override
  void dispose() {
    super.dispose();
    if (timer != null) {
      timer.cancel();
    }
  }

  List<LineChartBarData> getChartBars() {
    var dataCount = datas.length;
    List<FlSpot> askList = [];
    List<FlSpot> bidList = [];
    for (int i = 0; i < dataCount; i++) {
      var bean = datas[i];
      askList.add(FlSpot(i.toDouble(), bean.ask));
      bidList.add(FlSpot(i.toDouble(), bean.bid ));
    }
    LineChartBarData lineChartBarData_ask = LineChartBarData(
      isCurved: true,
      curveSmoothness: 0,
      color: c_df9e20,
      barWidth: 2,
      isStrokeCapRound: true,
      dotData: const FlDotData(show: false),
      belowBarData: BarAreaData(
        show: true,
        gradient: LinearGradient(
            colors: [Colors.white, c_df9e20]
                .map((color) => color.withOpacity(0.3))
                .toList(),
            begin: Alignment.bottomLeft,
            end: Alignment.topLeft),
      ),
      spots: selectTabObs.value==0?askList:bidList,
    );
    print('getChartBars');
    setTimeValue();
    return [lineChartBarData_ask];
  }

  FlTitlesData getChartTitle() {
    return FlTitlesData(
      rightTitles: const AxisTitles(
        sideTitles: SideTitles(showTitles: false),
      ),
      topTitles: const AxisTitles(
        sideTitles: SideTitles(showTitles: false),
      ),
      leftTitles: AxisTitles(
        sideTitles: SideTitles(
          getTitlesWidget: (value,meta){
            return leftTitleWidgets(value,meta);
          },
            reservedSize: 35,
            showTitles: true),
        drawBelowEverything: true,
      ),
      bottomTitles: const AxisTitles(
        sideTitles: SideTitles(showTitles: false),
      ),
    );
  }

  Widget leftTitleWidgets(double value, TitleMeta meta) {
    final style = TextStyle(
      color: c_bbbbbb,
      fontWeight: FontWeight.bold,
      fontSize: 9,
    );
    return SideTitleWidget(
      axisSide: meta.axisSide,
      space: 10,
      child: Text(value.toInt().toString(), style: style),
    );
  }

  void setTimeValue(){
    var startTime="";
    var endTime="";
    if (datas.length > 1) {
      print('FlTitlesData 1${datas[0].createTime}');
      print('FlTitlesData 2${datas.last.createTime}');
      var timeS = DateTime.fromMillisecondsSinceEpoch(
          int.parse(datas[0].createTime ?? "0") * 1000);
      var timeE = DateTime.fromMillisecondsSinceEpoch(
          int.parse(datas.last.createTime ?? "0") * 1000);
      var shour=timeS.hour<10? "0${timeS.hour}" : timeS.hour.toString();
      var sminute=timeS.minute<10? "0${timeS.minute}" : timeS.minute.toString();
      var syear=timeS.year.toString();
      var smonth=timeS.month<10? "0${timeS.month}" : timeS.month.toString();
      var sday=timeS.day<10? "0${timeS.day}" : timeS.day.toString();

      var ehour=timeE.hour<10? "0${timeE.hour}" : timeE.hour.toString();
      var eminute=timeE.minute<10? "0${timeE.minute}" : timeE.minute.toString();
      var eyear=timeE.year.toString();
      var emonth=timeE.month<10? "0${timeE.month}" : timeE.month.toString();
      var eday=timeE.day<10? "0${timeE.day}" : timeE.day.toString();

      if(selectTypeObs.value==0||selectTypeObs.value==1||selectTypeObs.value==2){
        startTime = "${shour}:${sminute}";
        endTime = "${ehour}:${eminute}";
      }else if(selectTypeObs.value==3||selectTypeObs.value==4){
        startTime = "${smonth}-${sday}";
        endTime = "${emonth}-${eday}";
      }
    }
    startTimeObs.value=startTime;
    endTimeObs.value=endTime;
  }


  String getTimeValue(int index){
    if(datas.length>index){
      var time=datas[index].createTime;
      var timeData = DateTime.fromMillisecondsSinceEpoch(
          int.parse(time ?? "0") * 1000);
      var hour=timeData.hour<10? "0${timeData.hour}" : timeData.hour.toString();
      var minute=timeData.minute<10? "0${timeData.minute}" : timeData.minute.toString();
      var month=timeData.month<10? "0${timeData.month}" : timeData.month.toString();
      var day=timeData.day<10? "0${timeData.day}" : timeData.day.toString();
      if(selectTypeObs.value==0||selectTypeObs.value==1||selectTypeObs.value==2){
        return "${hour}:${minute}";
      }else if(selectTypeObs.value==3||selectTypeObs.value==4){
        return  "${month}-${day}";
      }
    }
    return "";
  }
}
